﻿using CSRedis;
using EasyCaching.Core;
using EasyCaching.CSRedis;
using Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System;
using System.Collections.Generic;

public static class CsRedisExtensions
{
    /// <summary>
    /// 注册RedisHelper,CsRedisHelper
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    /// <returns></returns>
    public static IServiceCollection AddCsRedisHelperz(this IServiceCollection services, IConfiguration configuration, Action<CSRedisClient> configure = null)
    {
        var options = configuration.GetSection(CsRedisOptions.SectionName).Get<CsRedisOptions>();
        if (options == null) throw new ArgumentNullException("csredis配置不存在");
        var csredis = new CSRedisClient(options.ConnectionString);
        configure?.Invoke(csredis);
        RedisHelper.Initialization(csredis);
        CsRedisHelper.Initialization(csredis);
        return services;
    }

    /// <summary>
    /// 和EasyCaching共用同一个csredis实例,必须先注册AddEasyCachingExt
    /// </summary>
    /// <param name="app"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseCsRedisHelperByEasyCaching(this IApplicationBuilder app)
    {
        var csredis = app.ApplicationServices.GetRequiredService<EasyCachingCSRedisClient>();
        if (csredis != null)
        {
            RedisHelper.Initialization(csredis);
            CsRedisHelper.Initialization(csredis);
        }
        else
        {
            Log.Error("初始化RedisHelper失败");
        }
        return app;
    }
}
